package com.mall.b2c.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mall.b2c.util.SettingUtils;
import com.mall.common.bean.FileInfo;
import com.mall.common.bean.FileInfo.FileType;
import com.mall.common.bean.FileInfo.OrderType;
import com.mall.common.bean.Message;
import com.mall.common.controller.BaseController;
import com.mall.common.enums.UploadType;
import com.mall.common.service.FileService;
import com.mall.common.util.ResponseUtils;
import com.mall.common.util.UploadUtil;

@Controller
@RequestMapping("/admin/system/upload")
public class UploadController extends BaseController{

	@Resource private FileService fileService;
	
	@RequestMapping(value="/browser", method=RequestMethod.GET)
	@ResponseBody
	public List<FileInfo> browser(UploadType uploadType, String path, FileType fileType, OrderType orderType, String componentId){
		return fileService.browser(uploadType, path, fileType, orderType, componentId, SettingUtils.get());
	}
	
	@RequestMapping(value="/submit", method=RequestMethod.POST)
	public String submit(UploadType uploadType, FileType fileType, @RequestParam(value = "file", required = false) MultipartFile multipartFile, 
			String componentId, HttpServletResponse response){
		if (!fileService.isValid(fileType, multipartFile, SettingUtils.get())) {
			return ResponseUtils.ajaxJson(Message.error("admin.upload.invalid", null), response);
		} else {
			String path = null;
			path = fileService.upload(fileType, multipartFile, false, componentId, uploadType, null, SettingUtils.get());
			if (path == null){
				return ResponseUtils.ajaxJson(Message.error("admin.upload.invalid", null), response);
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("url", path);
			map.put("store_path", UploadUtil.pathToNative(path, componentId));
			return ResponseUtils.ajaxJson(map, response);
		}
	}
	
}
